// #ifdef APP-PLUS
import getAuth from 'common/getAuth.js'
// #endif
var tools = {
	// API基础URL配置
	httpOne: 'https://yuer.huizu.icu/api/', // 主域名地址
	upload: 'https://yuer.huizu.icu/api/common/upload', // 文件上传接口地址
	URL: 'https://yuer.huizu.icu',

	/**
	 * 显示消息提示框
	 * @param {String} title - 提示的内容
	 * @param {String} icon - 图标类型，默认为none，可选值：success/loading/none
	 */
	showtt: function(title, icon) {
		if (title && title.length > 0) {
			uni.showToast({
				title: title,
				duration: 2000,
				icon: icon ? icon : 'none'
			})
		}
	},
	getSatusBarHeight(height = 0) {
		// #ifdef MP-WEIXIN
		const windowInfo = wx.getWindowInfo()
		return height + windowInfo.statusBarHeight
		// #endif
		// #ifndef MP-WEIXIN
		const systemInfo = uni.getSystemInfoSync();
		return height + systemInfo.statusBarHeight;
		// #endif
	},
	/**
	 * 显示加载提示框
	 * @param {String} title - 提示的内容
	 * @param {Boolean} mask - 是否显示透明蒙层，默认false
	 */
	showload: function(title, mask = false) {
		if (title && title.length > 0) {
			uni.showLoading({
				title,
				mask
			})
		}
	},

	/**
	 * 统一路由跳转方法
	 * @param {String} method - 跳转方式：
	 *                         next-navigateTo(保留当前页面跳转)
	 *                         redirect-redirectTo(关闭当前页面跳转)
	 *                         switch-switchTab(跳转到tabBar页面)
	 *                         relaunch-reLaunch(关闭所有页面跳转)
	 *                         back-navigateBack(返回上一页)
	 * @param {Object|Number} parmas - 跳转参数对象或返回的层数
	 * @param {Boolean} isToken - 是否需要验证登录态
	 */
	goTo(method = 'back', parmas = null, isToken = false) {
		if (method == 'back') {
			uni.navigateBack({
				delta: parmas || 1,
				success: (res) => {
					console.log('goTo 跳转成功' + method, res)
				},
				fail: (err) => {
					console.log('goTo 跳转失败' + method, err)
					if (err.errMsg == 'navigateBack:fail cannot navigate back at first page.') {
						this.goTo('switch', '/pages/index/index')
					}
				},
			})
		} else {
			if (isToken) {
				let token = uni.getStorageSync('token')
				if (!token) {
					this.goTo('navigateTo', '/pages/login/login?path=' + encodeURIComponent(parmas.url) + '&type=1',
						false)
					return false
				}
			}
			if (parmas == null) {
				this.showtt('参数错误, 请传入parmas参数')
				return false
			}
			let methodsText = {
				'next': 'navigateTo',
				'redirect': 'redirectTo',
				'switch': 'switchTab',
				'relaunch': 'reLaunch',
				'back': 'navigateBack',
			}
			uni[methodsText[method]]({
				success: (res) => {
					console.log('goTo 跳转成功' + method, res)
				},
				fail: (err) => {
					console.log('goTo 跳转失败' + method, err)
				},
				url: parmas,
			})
		}
	},
	GetUrlParam(url, paraName) {
		var arrObj = url.split("?");

		if (arrObj.length > 1) {
			var arrPara = arrObj[1].split("&");
			var arr;

			for (var i = 0; i < arrPara.length; i++) {
				arr = arrPara[i].split("=");

				if (arr != null && arr[0] == paraName) {
					return arr[1];
				}
			}
			return "";
		} else {
			return "";
		}
	},
	/**
	 * 防抖函数 - 防止重复点击
	 * @param {Function} methods - 需要执行的函数
	 * @param {Any} info - 传递给执行函数的参数
	 */
	noMultipleClicks(methods, info) {
		// methods是需要点击后需要执行的函数， info是点击需要传的参数
		let that = this;
		if (that.noClick) {
			// 第一次点击
			that.noClick = false;
			if (info && info !== '') {
				// info是执行函数需要传的参数
				methods(info);
			} else {
				methods();
			}
			setTimeout(() => {
				that.noClick = true;
			}, 2000)
		} else {
			// 这里是重复点击的判断
		}
	},

	/**
	 * HTTP请求封装(JSON格式)
	 * @param {String} method - 请求方法(GET/POST等)
	 * @param {String} url - 请求地址
	 * @param {Object} data - 请求参数
	 * @param {String} showLoads - 加载提示文字，不传则不显示loading
	 * @returns {Promise} 
	 */
	axios: function(method, url, data, showLoads) {
		if (showLoads) {
			uni.showLoading({
				'title': showLoads
			})
		}; //加载中的框  showLoads
		return new Promise((resolve, reject) => {
			uni.request({
				url: this.httpOne + url, //请求地址 url
				data: data, //请求参数 data
				method: method, //请求格式 method POST GET
				header: {
					'Content-Type': 'application/json;charset=utf-8'
				},
				success: (res) => {
					if (showLoads) {
						uni.hideLoading()
					}
					resolve(res.data)
				},
				fail: (err) => {
					reject(err)
				},
				complete() {

				}
			})
		})
	},

	/**
	 * 表单格式HTTP请求封装(带Token验证)
	 * @param {String} method - 请求方法
	 * @param {String} url - 请求地址
	 * @param {Object} data - 请求参数
	 * @param {String} showLoads - 加载提示文字
	 * @returns {Promise}
	 */
	axiosFromToken: function(method, url, data, showLoads) {
		let token = uni.getStorageSync('token') ? uni.getStorageSync('token') : ''; //用户的token
		if (showLoads) {
			uni.showLoading({
				'title': showLoads
			})
		}; //加载中的框
		return new Promise((resolve, reject) => {
			uni.request({
				url: this.httpOne + url, //请求地址 url
				method: method, //请求格式 method POST GET
				data: data, //请求参数 data
				header: {
					'content-Type': 'application/x-www-form-urlencoded',
					'token': token
				},
				success: (res) => {
					if (showLoads) {
						uni.hideLoading()
					}
					if (res.statusCode == 401) {
						uni.showModal({
							title: '温馨提示',
							content: '尚未登录或登录已过期，是否前往登录？',
							success: (res) => {
								uni.clearStorageSync()
								this.goTo('next',
									'/pages/login/login?type=1&method=navigateBack',
									false)
							}
						});
						return false
					}
					resolve(res.data)
				},
				fail: (err) => {
					reject(err)
				},
				complete() {

				}
			})
		})
	},
	/*
	@param url 图片地址
	@param current 当前显示的图片索引
	@param isUrl 是否是图片地址
	@param key 对象key
	*/
	lookPhoto(url, current = 0, isUrl = false, key = '') { //查看图片
		let urls = []
		if (Array.isArray(url)) {
			urls = url
		} else {
			urls = [url]
		}
		if (key) {
			urls = urls.map(item => item[key])
		}
		console.log(urls, 'urls')
		if (isUrl) {
			urls = urls.map(item => this.URL + item)
		}
		console.log(urls, 'urls')
		uni.previewImage({
			current,
			urls,
			fail(err) {
				console.log(err, '报错')
			}
		})
	},
	// 跳转下一页
	goNext(url) {
		uni.navigateTo({
			url: url
		})
	},

	// 返回上一页
	goBack(num) {
		uni.navigateBack({
			delta: num
		})
	},

	// 跳转tabar页面
	goSwitchTab(url) {
		uni.switchTab({
			url: url
		})
	},

	// 关闭所有页面，跳转到指定页面
	goReLaunch(url) {
		uni.reLaunch({
			url: url
		})
	},

	// 关闭当前页，跳转下一页
	goRedirectTo(url) {
		uni.redirectTo({
			url: url
		})
	},

	throttle: function(fn, wait) {
		clearTimeout(this.timeout)
		let id = this.tabs[this.current].id
		this.timeout = setTimeout(() => {
			this.getList(id, this.current)
		}, 450)
	},

	getScrollHeight(titleH) { //获取元素铺满全屏的高度 uni.createSelectorQuery().select(".scroll")
		return new Promise((resolve, reject) => {
			setTimeout(() => {
				let system
				// #ifdef MP-WEIXIN
				const windowInfo = wx.getWindowInfo()
				system = windowInfo
				// #endif
				// #ifndef MP-WEIXIN
				system = uni.getSystemInfoSync()
				// #endif
				console.log(system, titleH)
				titleH.boundingClientRect(data => {
					console.log(data)
					resolve(system.windowHeight - data
						.top) //计算高度：元素高度=窗口高度-元素距离顶部的距离（data.top）
				}).exec()
			}, 10)
		})
	},

	//rpx转px
	rpxToPx(rpx) {
		let screenWidth
		// #ifdef MP-WEIXIN
		const windowInfo = wx.getWindowInfo()
		screenWidth = windowInfo.screenWidth
		// #endif
		// #ifndef MP-WEIXIN
		screenWidth = uni.getSystemInfoSync().screenWidth
		// #endif
		return (screenWidth * Number.parseInt(rpx)) / 750
	},

	//px转rpx
	pxToRpx(px) {
		let screenWidth
		// #ifdef MP-WEIXIN
		const windowInfo = wx.getWindowInfo()
		screenWidth = windowInfo.screenWidth
		// #endif
		// #ifndef MP-WEIXIN
		screenWidth = uni.getSystemInfoSync().screenWidth
		// #endif
		return (750 * Number.parseInt(px)) / screenWidth
	},

	async call(tel) {
		// #ifdef APP
		if (uni.getSystemInfoSync().platform === 'android') {
			let result = await getAuth.requestPermissions('CALL_PHONE')
			if (result !== 1) return
		}
		uni.makePhoneCall({
			phoneNumber: tel, //电话号码
			success(ress) {
				console.log("拨打电话成功", ress)
			},
			fail(err) {
				console.log("拨打电话失败", 'err')
			}
		});
		// #endif
		// #ifdef MP-WEIXIN
		uni.makePhoneCall({
			phoneNumber: tel, //电话号码
			success(ress) {
				console.log("拨打电话成功", ress)
			},
			fail(err) {
				console.log("拨打电话失败", 'err')
			}
		});
		// #endif
	},

	// 文件操作相关方法
	/**
	 * 下载并保存文件
	 * @param {String} file - 文件URL
	 * @param {Boolean} ifOpenFile - 下载后是否立即打开文件
	 */
	downloadFile(file, ifOpenFile) { //下载课件
		uni.showLoading({
			title: '请稍等',
			content: '正在下载文件',
			mask: true
		})
		uni.downloadFile({
			url: file, //下载地址接口返回
			success: async (data) => {
				if (data.statusCode === 200) {
					//文件保存到本地
					// #ifdef APP-PLUS
					if (uni.getSystemInfoSync().platform === 'android') {
						let result = await getAuth.requestPermissions('WRITE_EXTERNAL_STORAGE')
						if (result !== 1) return
					}
					// #endif
					uni.saveFile({
						tempFilePath: data.tempFilePath, //临时路径
						success: function(res) {
							uni.showToast({
								icon: 'none',
								mask: true,
								title: '文件已保存：' + res.savedFilePath, //保存路径
								duration: 3000,
							});
							if (ifOpenFile) {
								setTimeout(() => {
									//打开文档查看
									uni.openDocument({
										filePath: res.savedFilePath,
										success: function(res) {
											// console.log('打开文档成功');
										}
									});
								}, 1000)
							}
						},
						complete() {
							uni.hideLoading()
						}
					});
				}
			},
			fail: (err) => {
				uni.hideLoading()
				uni.showToast({
					icon: 'none',
					mask: true,
					title: '失败请重新下载',
				});
			},
		});
	},

	/**
	 * 保存图片到相册
	 * @param {String} url - 图片URL
	 */
	async saveImage(url) { //保存二维码
		const that = this
		uni.showLoading({
			title: '加载中'
		})
		// #ifdef APP-PLUS
		if (uni.getSystemInfoSync().platform === 'android') {
			let result = await getAuth.requestPermissions('WRITE_EXTERNAL_STORAGE')
			if (result !== 1) return
		}
		// #endif
		uni.downloadFile({
			url, //网络图片的地址
			success(res) {
				uni.saveImageToPhotosAlbum({
					filePath: res.tempFilePath, //临时文件地址
					success(res) {
						uni.showToast({
							title: '保存成功',
							icon: 'success'
						})
						uni.hideLoading()
					},
					fail(res) {
						uni.showToast({
							title: '保存失败',
							icon: 'error'
						})
						uni.hideLoading()
						console.log('保存错误', res);
					}
				})
			},
			fail(res) {
				console.log('保存错误', res);
			},
		})
	},

	// 数据处理相关方法
	/**
	 * 深拷贝对象
	 * @param {Object} obj - 需要拷贝的对象
	 * @returns {Object} 拷贝后的新对象
	 */
	copyObj(obj = {}) {
		//变量先置空
		let newobj = null;

		//判断是否需要继续进行递归
		if (typeof(obj) == 'object' && obj !== null) {
			newobj = obj instanceof Array ? [] : {};
			//进行下一层递归克隆
			for (var i in obj) {
				newobj[i] = this.copyObj(obj[i])
			}
			//如果不是对象直接赋值
		} else newobj = obj;

		return newobj;
	},

	/**
	 * 表单数据验证
	 * @param {Object} data - 需要验证的表单数据对象
	 * @param {Array} keys - 可选字段数组(这些字段可以为空)
	 * @returns {Boolean} 验证是否通过
	 */
	formInfo(data, keys) {
		let obj = {
			...data
		}
		// data 验证对象 Object
		// keys 验证对象中非必填字段 Array
		if (keys && keys[0]) {
			keys.forEach(val => {
				delete obj[val]
			})
		}
		let show = true
		for (let key in obj) {
			const value = obj[key]
			if (!value) {
				uni.showToast({
					title: '请检查信息是否填写',
					icon: 'none'
				})
				console.log(`未填写完整value => ${value}, key => ${key}`)
				show = false;
				break;
			}
		}
		return show;
	},

	// 判断身份证号    
	isSfz(idcard) {
		var id =
			/^[1-9][0-9]{5}(19|20)[0-9]{2}((01|03|05|07|08|10|12)(0[1-9]|[1-2][0-9]|31)|(04|06|09|11)(0[1-9]|[1-2][0-9]|30)|02(0[1-9]|[1-2][0-9]))[0-9]{3}([0-9]|x|X)$/
		if (idcard === '') {
			uni.showToast({
				title: '请输入身份证号',
				icon: 'none'
			})
		} else if (!id.test(idcard)) {
			uni.showToast({
				title: '身份证号格式不正确!',
				icon: 'none'
			})
			return false
		} else {
			return false
		}
	},

	// 判断是否是手机号   
	isPhone(val) {
		var patrn = /^(((1[3456789][0-9]{1})|(15[0-9]{1}))+\d{8})$/
		if (!patrn.test(val) || val === '') {
			uni.showToast({
				title: '手机号格式不正确',
				icon: 'none'
			})
			return false
		} else {
			return true
		}
	},

	// 判断邮箱
	isEmail(email) {
		if (email.search(/^\w+((-\w+)|(\.\w+))*\@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+$/) != -1)
			return true;
		else
			return false;
	},

	//当前日期
	data() {
		var now = new Date(),
			y = now.getFullYear(),
			m = now.getMonth() + 1,
			d = now.getDate();
		let Time = y + "-" + (m < 10 ? "0" + m : m) + "-" + (d < 10 ? "0" + d : d)
		return Time
	},

	//当前时间
	time() {
		var now = new Date(),
			y = now.getFullYear(),
			m = now.getMonth() + 1,
			d = now.getDate();
		let Time = y + "-" + (m < 10 ? "0" + m : m) + "-" + (d < 10 ? "0" + d : d) + "-" + now.toTimeString()
			.substr(0, 8)
		let str = y + "-" + (m < 10 ? "0" + m : m) + "-" + (d < 10 ? "0" + d : d) + "T" + now.toTimeString().substr(
			0, 8)
		console.log(str, 'str')
		return Time
	},

	//时间转时间戳
	timeTotimeStamp(time) {
		let timestamp = Date.parse(new Date(time).toString());
		//timestamp = timestamp / 1000; //时间戳为13位需除1000，时间戳为13位的话不需除1000
		return timestamp;
		//2021-11-18 22:14:24的时间戳为：1637244864707
	},

	//时间日期处理相关方法
	/**
	 * 计算两个时间之间的差值
	 * @param {Date|String} startime - 开始时间
	 * @param {Date|String} endTime - 结束时间
	 * @returns {Object} 包含天、时、分、秒的对象
	 */
	timeDifference(startime, endTime) {
		const stime = new Date(startime).getTime();
		const etime = new Date(endTime).getTime();
		const diffTime = etime - stime;
		const day = Math.floor(diffTime / (1000 * 60 * 60 * 24));
		const hour = Math.floor(diffTime / (1000 * 60 * 60) % 24);
		const minute = Math.floor(diffTime / (1000 * 60) % 60);
		const second = Math.floor(diffTime / 1000 % 60);
		let obj = {
			day,
			hour,
			minute,
			second,
			timeText: `${day}天${hour}时${minute}分${second}秒`
		}
		return obj
	},

	//时间戳计算时间差
	timestampDifference(startime, endTime) {
		const diffTime = endTime - startime;
		const day = Math.floor(diffTime / (60 * 60 * 24));
		const hour = Math.floor(diffTime / 60 / 60 % 24);
		const minute = Math.floor(diffTime / 60 % 60);
		const second = Math.floor(diffTime % 60);
		let obj = {
			day,
			hour,
			minute,
			second,
			timeText: `${day}天${hour}时${minute}分${second}秒`
		}
		return obj
	},

	/**
	 * 时间戳转换为日期时间
	 * @param {Number} timestamp - 10位时间戳
	 * @returns {Object} 包含年月日时分秒的对象
	 */
	timestampToTime(timestamp) {
		timestamp *= 1000
		var date = new Date(timestamp); //时间戳为10位需*1000，时间戳为13位的话不需乘1000
		var Y = date.getFullYear();
		var M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1);
		var D = (date.getDate() < 10 ? '0' + date.getDate() : date.getDate());
		var h = (date.getHours() < 10 ? '0' + date.getHours() : date.getHours());
		var m = (date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes());
		var s = (date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds());
		let obj = {
			Y,
			M,
			D,
			h,
			m,
			s,
			time: `${Y}-${M}-${D} ${h}:${m}:${s}`,
			data: `${Y}-${M}-${D}`
		};
		return obj
	},

	getDays() { //获取未来n天的日期信息
		var leng = 7;
		var now = new Date();
		var nowTime = now.getTime();
		var oneDayTime = 24 * 60 * 60 * 1000;
		var date = []
		for (var i = 0; i < leng; i++) {
			var dateItem = {
				date: '',
				text: ''
			}
			//显示星期
			var ShowTime = nowTime + i * oneDayTime;
			//初始化日期时间
			var myDate = new Date(ShowTime);
			var year = myDate.getFullYear();
			var month = myDate.getMonth() + 1;
			var date = myDate.getDate();
			dateItem.text = "星期" + "日一二三四五六".charAt(myDate.getDay());
			dateItem.date = year + "-" + month + "-" + date;
			dateItem.select = 0;
			dateItem.year = year;
			dateItem.month = month;
			dateItem.day = date;
			if (i == 0) dateItem.text = '今天'
			if (i == 1) dateItem.text = '明天'
			if (i == 2) dateItem.text = '后天'
			date.push(dateItem);
		}
		return date
		console.log(date)
	},

	/**
	 * 判断是否是中文
	 * @param str
	 * @returns {Boolean}
	 */
	isChine: function(str) {
		var reg = /^([u4E00-u9FA5]|[uFE30-uFFA0])*$/;
		if (reg.test(str)) {
			return false;
		}
		return true;
	},

	/**
	 * 判断是否是中文
	 * @param num
	 * @returns {String | Number}
	 */
	isForNumber(num) {
		num = Number(num);
		if (num == 0) {
			return num + '';
		} else
		if (num > 1 && num < 10000) {
			return num + '';
		} else {
			return (num / 10000).toFixed(2) + '万';
		}
	},

	/*验证是否为图片*/
	tmCheckImage: function(fileName) {
		return /(gif|jpg|jpeg|png|GIF|JPG|PNG)$/ig.test(fileName);
	},

	/*验证是否为视频*/
	tmCheckVideo: function(fileName) {
		return /(mp4|mp3|flv|wav)$/ig.test(fileName);
	},

	// 判断密码是否符合 至少6位,包括大小写字母、数字、特殊字符
	isPassword(val) {
		var reg = /^(?![0-9]+$)(?![a-z]+$)(?![A-Z]+$)(?!([^(0-9a-zA-Z)])+$)^.{8,16}$/;
		if (val === '') {
			uni.showToast({
				title: '请输入密码',
				icon: 'none'
			})
		} else if (!reg.test(val)) {
			uni.showToast({
				title: '至少6位,包括大小写字母、数字、特殊字符',
				icon: 'none'
			})
			return false
		} else {
			return true
		}
	},

	copyTextH5App(info) {
		if (!info) return false;
		info = info + '';
		// #ifndef H5
		uni.setClipboardData({ //准备复制的数据
			data: info + '',
			success: function(res) {
				uni.showToast({
					title: '复制成功'
				});
			}
		})
		// #endif
		// #ifdef H5
		let result
		let textarea = document.createElement("textarea")
		textarea.value = info
		textarea.readOnly = "readOnly"
		document.body.appendChild(textarea)
		textarea.select() // 选中文本内容
		textarea.setSelectionRange(0, info.length) // 设置选定区的开始和结束点

		result = document.execCommand("copy") //将当前选中区复制到剪贴板
		// console.log('[result]', result);
		if (result) {
			uni.showToast({ //提示
				title: '复制成功'
			})
		} else {
			uni.showToast({ //提示
				title: '复制失败，请重新尝试',
				icon: 'none'
			})
		}
		textarea.remove()
		// #endif
	},
}


export default tools;